package com.foogui.unittest.service;

import com.foogui.unittest.dao.UserDAO;
import com.foogui.unittest.entity.UserDO;
import com.foogui.unittest.utils.IdGenerator;
import com.foogui.unittest.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class UserService {

    @Autowired
    private UserDAO userDAO;


    @Value("${userService.canModify}")
    private Boolean canModify;


    /**
     * 保存用户
     *
     * @param userVO 用户保存
     * @return 用户标识
     */
    public Long saveUser(UserVO userVO) {
        // 获取用户标识
        Long userId = userDAO.getIdByName(userVO.getUsername());

        //  不存在则创建
        if (Objects.isNull(userId)) {
            Long id = IdGenerator.next();
            UserDO userCreateDO = new UserDO();
            userCreateDO.setId(id);
            userCreateDO.setUsername(userVO.getUsername());
            userDAO.create(userCreateDO);
        }else if (Boolean.TRUE.equals(canModify)) {
            UserDO userModifyDO = new UserDO();
            userModifyDO.setId(userId);
            userModifyDO.setUsername(userVO.getUsername());
            userDAO.modify(userModifyDO);
        }else {
            throw new UnsupportedOperationException("不支持修改");
        }
        // 返回用户标识
        return userId;
    }
}
